package com.cameron.controller;

import com.cameron.service.MsmService;
import com.cameron.utils.Result;
import com.cameron.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm-service")
@CrossOrigin
@Slf4j
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result sendMsm(@PathVariable String phone) {

        //先从redis中获取验证码
        String res = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotEmpty(res)) {
            log.info("短信中心缓存验证码：{}",res);
            return Result.ok();
        }

        //生成随机四位验证码，传递到阿里云发送
        String code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean success = msmService.sendMessage(phone, param);
        if (success) {
            //若发送成功则将数据保存到redis中 设置保存时间为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.error().message("短信发送失败！");
    }
}
